package com.shbaiche.bifenba.ui.match;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cpoopc.scrollablelayoutlib.ScrollableLayout;
import com.google.gson.Gson;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.shbaiche.bifenba.App;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.model.Event;
import com.shbaiche.bifenba.model.base.BoolValue;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.data.CompeteVo;
import com.shbaiche.bifenba.model.data.TeamFollowMessage;
import com.shbaiche.bifenba.model.match.EaseChatMessage;
import com.shbaiche.bifenba.model.match.EasePhotoMessage;
import com.shbaiche.bifenba.model.match.MatchesInfoMessage;
import com.shbaiche.bifenba.model.match.MatchesLineupMessage;
import com.shbaiche.bifenba.model.match.MatchesVo;
import com.shbaiche.bifenba.model.user.FollowCancelMessage;
import com.shbaiche.bifenba.model.user.FollowUpdateMessage;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.base.BaseActivity;
import com.shbaiche.bifenba.ui.base.XStateFragmentAdapter;
import com.shbaiche.bifenba.ui.data.DataScheduleFragment;
import com.shbaiche.bifenba.ui.data.DataTeamDetailActivity;
import com.shbaiche.bifenba.ui.data.DataTeamDetailInfoFragment;
import com.shbaiche.bifenba.ui.data.DataTeamDetailMemberFragment;
import com.shbaiche.bifenba.ui.home.CategoryTabStrip;
import com.shbaiche.bifenba.ui.my.CollectionFragment;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;
import com.shbaiche.bifenba.view.CircularImage;
import com.shbaiche.bifenba.view.NoScrollViewPager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroid.event.BusFactory;
import cn.droidlover.xdroidbase.base.XFragmentAdapter;
import cn.droidlover.xdroidbase.imageloader.ILFactory;
import cn.droidlover.xdroidbase.router.Router;
import okhttp3.Call;


/**
 * 比赛对阵详情
 */

public class MatchDetailActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;

    @BindView(R.id.iv_follow)
    ImageView ivFollow;

    @BindView(R.id.iv_logo_home)
    CircularImage ivLogoHome;

    @BindView(R.id.iv_logo_visit)
    CircularImage ivLogoVisie;

    @BindView(R.id.tv_name_home)
    TextView tvNameHome;

    @BindView(R.id.tv_name_visit)
    TextView tvNameVisie;

    @BindView(R.id.tv_desc)
    TextView tvDesc;

    @BindView(R.id.tv_score)
    TextView tvScore;

    @BindView(R.id.tv_status)
    TextView tvStatus;


    @BindView(R.id.layout_title)
    LinearLayout layoutTitle;

    @BindView(R.id.layout_head)
    LinearLayout layoutHead;

    //@BindView(R.id.scrollableLayout)
    //ScrollableLayout scrollableLayout;

    @BindView(R.id.category_strip)
    CategoryTabStrip tabs;

    @BindView(R.id.view_pager)
    ViewPager pager;

    @BindView(R.id.app_bar)
    AppBarLayout appBarLayout;

    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout collapsingToolbarLayout;

    @BindView(R.id.toolbar)
    Toolbar toolbar;



    List<Fragment> fragmentList = new ArrayList<>();
    XStateFragmentAdapter adapter;

    MatchesVo matchesVo;

    MatchesInfoMessage matchesInfo;

    private Dialog dg;

    private String mRoomId = "";
    private int num = 0;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    //listener(msg.obj.toString());
                    ToastUtil.show("加入聊天室成功");
                    break;
                case 1:
                    ToastUtil.show(msg.obj.toString());
                    break;
                case 2:
                    loadFragment();
                    break;

            }
        }
    };

    /**
     * 申请权限
     */
    @SuppressLint("NewApi")
    private void applyPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 88);
        }
    }

    /**
     * 使用CollapsingToolbarLayout必须把title设置到CollapsingToolbarLayout上，
     * 设置到Toolbar上则不会显示
     */
    private void setTitleToCollapsingToolbarLayout() {
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                //Log.e("t","onOffsetChanged:"+verticalOffset);
                if (verticalOffset <= -layoutHead.getHeight() / 2) {

                    float alpha = (float) verticalOffset/-layoutHead.getHeight();

                    //Log.e("t","alpha:"+alpha);
                    layoutTitle.setAlpha(alpha);

                    //toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

                    //collapsingToolbarLayout.setTitle("黄晓果");
                    //使用下面两个CollapsingToolbarLayout的方法设置展开透明->折叠时你想要的颜色
                    collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));
                    collapsingToolbarLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.colorAccent));
                } else {
                    collapsingToolbarLayout.setTitle("");
                    layoutTitle.setAlpha(0);
                    //toolbar.setBackgroundColor(Color.TRANSPARENT);
                }
            }
        });
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }



        layoutTitle.setAlpha(0);

//        scrollableLayout.setOnScrollListener(new ScrollableLayout.OnScrollListener() {
//            @Override
//            public void onScroll(int currentY, int maxY) {
//                int headHeight = layoutHead.getHeight();
//
//                if(currentY > 0 && headHeight > 0){
//                    float scale = 0f;
//                    if(currentY < headHeight){
//                        scale = (float) currentY / headHeight;
//                    }else{
//                        scale = 1f;
//                    }
//
//                    layoutTitle.setAlpha(scale);
//
////                    layoutTitleLogo.setVisibility(View.VISIBLE);
////                    layoutTitleLogo.setAlpha(scale);
////                    layoutTitleLogo.setScaleX(scale);
////                    layoutTitleLogo.setScaleY(scale);
//
//                    //mTitleTxt.setVisibility(View.GONE);
//                }else{
//                    //layoutTitleLogo.setVisibility(View.GONE);
//                    //mTitleTxt.setVisibility(View.VISIBLE);
//                }
//            }
//        });



        matchesVo = (MatchesVo) getIntent().getSerializableExtra("data");

        if(matchesVo!=null){
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                applyPermission();
            }
            dg = new Dialog(this);
            dg.setContentView(R.layout.view_loading);

            setViews(matchesVo);



            loadData();

            getRoomId();

            //listener();

            EaseUI.getInstance().setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {

                @Override
                public EaseUser getUser(String username) {
                    EaseUser user = new EaseUser(username);
                    if(username.equals(App.mBBSName)){
                        user.setNickname(App.getPassport().getNickName());
                        user.setAvatar(App.getPassport().getPhotoPath());
                        return user;
                    }

                    if(mapInfos.containsKey(username)){
                        user.setNickname(mapInfos.get(username).getNickName());
                        user.setAvatar(mapInfos.get(username).getPhoto());
                        return user;
                    }else{
                        loadUserInfo(username);
                        if(mapInfos.containsKey(username)){
                            user.setNickname(mapInfos.get(username).getNickName());
                            user.setAvatar(mapInfos.get(username).getPhoto());
                            return user;
                        }else{
                            return user;
                        }

                    }

                }
            });

        }else{
            Log.e("e"," finish();");
            finish();
        }

    }

    private static HashMap<String,EasePhotoMessage> mapInfos = new HashMap<>();


    private void loadUserInfo(final String username){
        EasePhotoMessage message = new EasePhotoMessage();
        message.setUserName(username);

        NetApi.easePhoto(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());

            }

            @Override
            public void onResponse(TransMessage response, int id) {
                EasePhotoMessage result =new Gson().fromJson(response.getMessage(),EasePhotoMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null && result.getNickName()!=null){
                        Log.e("t","获取头像: "+result.getPhoto());
                        mapInfos.put(username,result);

                    }
                }else{
                    ToastUtil.show(response.getMessage());
                }
            }
        });
    }

    private void loadFragment(){
        fragmentList.clear();

        Bundle bundle = new Bundle();
        bundle.putSerializable("data",matchesVo);

        EaseChatFragment chatFragment = new EaseChatFragment();
        //传入参数
        Bundle args = new Bundle();
        args.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_CHATROOM);
        args.putString(EaseConstant.EXTRA_USER_ID, mRoomId);
        args.putInt("num", num);
        chatFragment.setArguments(args);

        MatchDetailBBSFragment fragmentBBS = new MatchDetailBBSFragment();
        fragmentBBS.setArguments(bundle);
        fragmentList.add(chatFragment);

        MatchDetailLiveFragment fragmentLive = new MatchDetailLiveFragment();
        fragmentLive.setArguments(bundle);
        fragmentList.add(fragmentLive);

        MatchDetailLineupFragment fragmentLineup = new MatchDetailLineupFragment();
        fragmentLineup.setArguments(bundle);
        fragmentList.add(fragmentLineup);

        MatchDetailAnalysisFragment fragmentAnalysis = new MatchDetailAnalysisFragment();
        fragmentAnalysis.setArguments(bundle);
        fragmentList.add(fragmentAnalysis);

        MatchDetailIntelligenceFragment fragmentIntelligence = new MatchDetailIntelligenceFragment();
        fragmentIntelligence.setArguments(bundle);
        fragmentList.add(fragmentIntelligence);

        MatchDetailOddsFragment fragmentOdds = new MatchDetailOddsFragment();
        fragmentOdds.setArguments(bundle);
        fragmentList.add(fragmentOdds);


        //fragmentList.add(new MatchDetailBBSFragment(matchesVo));

        if (adapter == null) {
            adapter = new XStateFragmentAdapter(getSupportFragmentManager(), fragmentList, new String[]{"聊天室","赛况","阵容","分析","情报","赔率"});
        }

        pager.setAdapter(adapter);

        tabs.setViewPager(pager);
        tabs.setAdaptive(true);

        Log.e("t","loadFragment");
    }

    public void getRoomId() {
        EaseChatMessage message = new EaseChatMessage();
        message.setGameType(matchesVo.getGameType());
        message.setGameId(matchesVo.getGameId());
        message.setCompeteId(matchesVo.getCompeteId());

        NetApi.easeChat(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());

            }

            @Override
            public void onResponse(TransMessage response, int id) {
                EaseChatMessage result =new Gson().fromJson(response.getMessage(),EaseChatMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null && result.getChatId()!=null){
                        Log.e("t","聊天室id: "+result.getChatId());
                        mRoomId = result.getChatId();
                        num = Integer.valueOf(""+result.getNum());
                        //tvNum.setText(""+result.getNum());
                        //joinRoom(result.getChatId());
                        handler.sendEmptyMessage(2);
                    }
                }else{
                    ToastUtil.show(response.getMessage());
                }
            }
        });

    }

    private void joinRoom(final String roomId){

        //roomId为聊天室ID
        EMClient.getInstance().chatroomManager().joinChatRoom(roomId, new EMValueCallBack<EMChatRoom>() {

            @Override
            public void onSuccess(EMChatRoom value) {
                //加入聊天室成功
                Log.e("t","加入聊天室成功");
                //listener(value.getName());
                mRoomId = roomId;
                Message msg= new Message();
                msg.what = 0;
                msg.obj = value.getId();
                handler.sendMessage(msg);

                //handler.sendEmptyMessage(2);


            }

            @Override
            public void onError(final int error, String errorMsg) {
                //加入聊天室失败
                Log.e("t","加入聊天室失败");

                Message msg= new Message();
                msg.what = 1;
                msg.obj = "加入聊天室失败";
                handler.sendMessage(msg);
                //handler.sendEmptyMessage(2);
            }
        });
    }

    public void loadData() {
        MatchesInfoMessage message = new MatchesInfoMessage();
        message.setPassport(App.getPassport());
        message.setCompeteId(matchesVo.getCompeteId());
        message.setGameType(matchesVo.getGameType());
        message.setGameId(matchesVo.getGameId());

        NetApi.matchesInfo(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {

                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onError(Call call, Exception e, int id) {

                ToastUtil.show("onFail" + e.getMessage());

            }

            @Override
            public void onResponse(TransMessage response, int id) {

                MatchesInfoMessage result = new Gson().fromJson(response.getMessage(), MatchesInfoMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if (result != null) {
                        Log.e("t", "onResponse");
                        matchesVo.setBrowseNum(result.getVo().getBrowseNum());
                        setFollowViews(result);
                        setViews(result.getVo());
                        //BusFactory.getBus().post(new Event.MatchesVoEvent(result.getVo()));
                    }
                } else {
                    Log.e("t", "onResponse getCode " + response.getCode());
                }
            }
        });
    }

    private void setViews(MatchesVo item){
        if(item!=null){
            ILFactory.getLoader().loadNet(ivLogoHome, item.getHomeLogo(), null);
            ILFactory.getLoader().loadNet(ivLogoVisie, item.getVisitLogo(), null);

            tvNameHome.setText(item.getHomeName());
            tvNameVisie.setText(item.getVisitName());
            tvDesc.setText(item.getDate() +" " +item.getCompeteName()+" ");
            tvScore.setText(item.getHomeScore()+":"+item.getVisitScore());
            if(item.getStatus()!=null){
                tvStatus.setText(item.getStatus().getText());
            }
        }
    }

    private void setFollowViews(MatchesInfoMessage message){
        if(message!=null){
            matchesInfo = message;
            ivFollow.setVisibility(View.VISIBLE);
            ivFollow.setImageResource(message.getIsFollow() == BoolValue.YES ? R.drawable.btn_follow_red : R.drawable.btn_follow_white);
        }
    }

    public void postFollow() {
        if(App.getPassport()==null){
            ToastUtil.show("请先登录");
            return;
        }
        dg.show();
        TeamFollowMessage message = new TeamFollowMessage();
        message.setPassport(App.getPassport());
        message.setTeamId(matchesVo.getGameId());
        message.setGameType(matchesVo.getGameType());
        message.setType(FollowUpdateMessage.FollowType.MATCHES);

        NetApi.teamFollow(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
                dg.dismiss();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
                dg.dismiss();
            }

            @Override
            public void onResponse(TransMessage response, int id) {
                dg.dismiss();
                TeamFollowMessage result =new Gson().fromJson(response.getMessage(),TeamFollowMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null){
                        Log.e("t","onResponse");
                        loadData();
                        ToastUtil.show(result.getMessage());

                    }
                }else{
                    Log.e("t","onResponse getCode "+response.getCode());
                    ToastUtil.show(result.getMessage());
                }
            }
        });
    }

    public void cancelFollow() {
        dg.show();
        FollowCancelMessage message = new FollowCancelMessage();
        message.setPassport(App.getPassport());
        message.setFollowId(matchesVo.getGameId());
        message.setGameType(matchesVo.getGameType());
        message.setType(FollowUpdateMessage.FollowType.MATCHES);

        NetApi.followCancel(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
                dg.dismiss();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
                dg.dismiss();

            }

            @Override
            public void onResponse(TransMessage response, int id) {
                dg.dismiss();
                FollowCancelMessage result =new Gson().fromJson(response.getMessage(),FollowCancelMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null){
                        Log.e("t","onResponse");
                        loadData();
                        ToastUtil.show(result.getMessage());

                    }
                }else{
                    Log.e("t","onResponse getCode "+response.getCode());
                    ToastUtil.show(result.getMessage());
                }
            }
        });
    }


    @Override
    public void setListener() {

    }

    @OnClick({
            R.id.iv_logo_home,
            R.id.iv_logo_visit,
            R.id.iv_follow,
            R.id.iv_back
    })
    public void clickEvent(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_logo_home:
                intent = new Intent(this,DataTeamDetailActivity.class);
                intent.putExtra(DataTeamDetailActivity.KEY_GAMETYPE,matchesVo.getGameType());
                intent.putExtra(DataTeamDetailActivity.KEY_TEAMID,matchesVo.getHomeId());
                startActivity(intent);
               break;
            case R.id.iv_logo_visit:
                intent = new Intent(this,DataTeamDetailActivity.class);
                intent.putExtra(DataTeamDetailActivity.KEY_GAMETYPE,matchesVo.getGameType());
                intent.putExtra(DataTeamDetailActivity.KEY_TEAMID,matchesVo.getVisitId());
                startActivity(intent);
                break;
            case R.id.iv_follow:
                if(matchesInfo!=null){
                    if(matchesInfo.getIsFollow() == BoolValue.YES){
                        cancelFollow();
                    }else{
                        postFollow();
                    }
                }
                break;
            case R.id.iv_back:
                finish();
                break;

        }
    }

    public static void launch(Activity activity) {
        Router.newIntent()
                .from(activity)
                .to(MatchDetailActivity.class)
                .data(new Bundle())
                .launch();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_match_detail;
    }

    @Override
    public void setToolbar() {

        setSupportActionBar(toolbar);

        setTitleToCollapsingToolbarLayout();

    }

    private void listener(){

        //SDK初始化加载的聊天记录为20条，到顶时需要去DB里获取更多
        //获取startMsgId之前的pagesize条消息，此方法获取的messages SDK会自动存入到此会话中，APP中无需再次把获取到的messages添加到会话中
        //List<EMMessage> messages = conversation.loadMoreMsgFromDB(startMsgId, pagesize);

        msgListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //收到消息
                Log.e("t","收到消息");

            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
                Log.e("t","收到透传消息");
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
                //收到已读回执
                Log.e("t","收到已读回执");
            }

            @Override
            public void onMessageDelivered(List<EMMessage> message) {
                //收到已送达回执
                Log.e("t","收到已送达回执");
            }
            @Override
            public void onMessageRecalled(List<EMMessage> messages) {
                //消息被撤回
                Log.e("t","消息被撤回");
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
                Log.e("t","消息状态变动");
            }
        };

        roomChangeListener = new EMChatRoomChangeListener() {
            @Override
            public void onChatRoomDestroyed(String s, String s1) {
                Log.e("t","onChatRoomDestroyed");
            }

            @Override
            public void onMemberJoined(String s, String s1) {
                Log.e("t","onMemberJoined");
            }

            @Override
            public void onMemberExited(String s, String s1, String s2) {
                Log.e("t","onMemberExited");
            }

            @Override
            public void onRemovedFromChatRoom(int i, String s, String s1, String s2) {
                Log.e("t","onRemovedFromChatRoom");
            }

            @Override
            public void onMuteListAdded(String s, List<String> list, long l) {
                Log.e("t","onMuteListAdded");
            }

            @Override
            public void onMuteListRemoved(String s, List<String> list) {
                Log.e("t","onMuteListRemoved");
            }

            @Override
            public void onAdminAdded(String s, String s1) {
                Log.e("t","onAdminAdded");
            }

            @Override
            public void onAdminRemoved(String s, String s1) {
                Log.e("t","onAdminRemoved");
            }

            @Override
            public void onOwnerChanged(String s, String s1, String s2) {
                Log.e("t","onOwnerChanged动");
            }

            @Override
            public void onAnnouncementChanged(String s, String s1) {
                Log.e("t","onAnnouncementChanged");
            }
        };

        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(roomChangeListener);

        Log.e("t","开始监听：");

    }

    EMMessageListener msgListener;

    EMChatRoomChangeListener roomChangeListener;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(msgListener!=null){
            EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        }
        if(roomChangeListener!=null){
            EMClient.getInstance().chatroomManager().removeChatRoomListener(roomChangeListener);
        }
    }



}
